<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\7\19 0019
 * Time: 16:32
 */
namespace app\api\model;
use think\Db;
use think\Model;
use think\Request;

class UserModel extends Model
{
    /**用户登录模型
     * @param Request $requerst
     * @return bool|string
     */
    public static function login(Request $requerst){
        $js_code = $requerst->param('js_code',null);
        $token  = $requerst->param('token',null);
        $inviter = $requerst->param('id',null);
        if(!$js_code){
            return ['code'=>404,'msg'=>'请输入openid'];
        }
        $resu = Db::connect();
        //通过openid查询是否有这个用户
        $appId = 'wx701da027293651ef';
        $appSecret = '53a2699885753486cf9cbcc0a21f7420';
        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$appSecret.'&js_code='.$js_code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        $json_obj = json_decode($res,true);
        $openid = $json_obj['openid'];
        if($openid){
            $user = $resu->name('p_management')->where('openid',$openid)->find();
        }elseif($token){
            $user = $resu->name('p_management')->where('token',$token)->find();
        }else{
            return ['code'=>404,'msg'=>'请输入openid'];
        }
        //生成token
        if($openid){
            $token = md5(uniqid().$openid);
        }else{
            $token = md5(uniqid().$user['openid']);
        }

        //讲获取的数据组装，openid和token
        if($openid){
            $data = ['openid'=>$openid,'token'=>$token];
        }else{
            $data = ['openid'=>$user['openid'],'token'=>$token];
        }
        //组装昵称
        $nickname = $requerst->param('nickname',null);
        if($nickname){
            $data['nickname'] = $nickname;
        }
        //组装头像网站地址
        $portrait = $requerst->param('avatarUrl',null);
        if($portrait){
            $data['H_portrait'] = $portrait;
        }
        if(!$user){
            //添加数据
           if($resu->name('p_management')->insert($data)){
                //添加朋友
               if($inviter){
                   $bool = UserModel::add_frend($openid,$inviter);
                   if(!$bool){
                       return ['code'=>409,'msg'=>'添加朋友失败'];
                   }
               }
                return ['code'=>200,'data'=>$token,'user'=>$user];
           } else{
               return ['code'=>403,'msg'=>'添加失败'];
           }
        }else{
            //如果注册了，组装推荐人
            if($inviter){
                $bool = UserModel::add_frend($user['openid'],$inviter);
                if(!$bool){
                    return ['code'=>409,'msg'=>'添加朋友失败'];
                }
            }
            //添加数据
            //return $resu->name('p_management')->where('openid',$openid)->update($data);
            if($resu->name('p_management')->where('openid',$openid)->update($data)){
                return ['code'=>200,'data'=>$token,'user'=>$user];
            }else{
                return ['code'=>403,'msg'=>'添加失败'];
            }
        }
    }

    /**验证是否存在token
     * @param $token
     * @return array|bool|false|\PDOStatement|string|Model
     */
    public static function istoken($token){
        $user = Db::name('p_management')->where('token',$token)->find();
        if(!$user){
            return false;
        }
        return $user;
    }

    /**添加分数
     * @param Request $request
     * @return array|bool|false|\PDOStatement|string|Model
     */
    public static function add_fraction(Request $request){
        $token = $request->param('token',null);
        $fraction = $request->param('fraction',0);
        if(!$token){
            return ['code'=>408,'msg'=>'参数错误'];
        }
        //获取当前用户信息
        $user = UserModel::getUser(['token'=>$token]);
        if(!$user){
            return ['code'=>402,'msg'=>'账号不存在'];
        }
         //讲分数加上
        $user['total_integral'] = $user['total_integral']+$fraction;
        //更新数据
        if(UserModel::updateUser($user)){
            return ['code'=>200,'data'=>$user];
        }else{
            return ['code'=>403,'msg'=>'更新错误'];
        }
    }

    /**更新User客户实例数据（p_management表）
     * @param $data
     * @return bool
     */
    public static function updateUser($data){
        //根据id更新数据
        if(isset($data['id'])){
            if(Db::name('p_management')->where('id',$data['id'])->update($data)){
                return true;
            }else{
                return false;
            }
             //更具token更新数据
        }elseif(isset($data['token'])){
            if(Db::name('p_management')->where('token',$data['token'])->update()){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**查找User模型数据（p_management）
     * @param array $data
     * @return array|bool|false|\PDOStatement|string|Model
     */
    public static function getUser(array $data){
        //根据id获取数据
        if(isset($data['id'])){
            if(is_array($data['id'])){
                $array =  Db::name('p_management')->where('id','in',$data['id'])->select();
            }else{
                $array = Db::name('p_management')->where('id',$data['id'])->find();
            }
            //根据token获取数据
        }elseif($data['token']){
            if(is_array($data['token'])){
                $array =  Db::name('p_management')->where('token','in',$data['token'])->select();
            }else{
                $array = Db::name('p_management')->where('token',$data['token'])->find();
            }
        }else{
            return false;
        }
        return $array;
    }

    /**向User添加数据
     * @param $data
     * @return bool
     */
    public static function addUser($data){
        if(Db::name('p_management')->insert($data)){
            return true;
        }else{
            return false;
        }
    }

    /**user删除数据
     * @param $data
     * @return bool
     */
    public static function deleteUser($data){
        //根据id删除数据
        if(isset($data['id'])){
            if(Db::name('p_management')->where('id','in',$data['id'])->delete()){
                return true;
            }else{
                return false;
            }
            //根据token删除数据
        }elseif(isset($data['token'])){
            if(Db::name('p_management')->where('token','in',$data['token'])->delete()){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**为openid的推荐人添加朋友
     * @param $openid：本人的openid
     * @param $inviter：推荐人的openid
     * @return bool
     */
    public static function add_frend($openid,$inviter){
        $resul = Db::connect();
        //组装数据给openid添加friend
        $friend = $resul->name('p_management')->where('openid',$inviter)->find();
        $user = $resul->name('p_management')->where('openid',$openid)->find();
        if($friend['friend']){
            $array1 = json_decode($friend['friend'],true);
            if(!in_array($openid,$array1)){
                $array1[] = $openid;
            }
        }else{
            $array1[] = $openid;
        }
        $friend['friend'] = json_encode($array1);
        if($user['friend']){
            $array2 = json_decode($user['friend'],true);
            if(!in_array($inviter,$array2)){
                $array2[] = $inviter;
            }
        }else{
            $array2[] =  $inviter;
        }
        $user['friend'] = json_encode($array2);
        $resul->name('p_management')->where('openid',$openid)->update($user);
        $resul->name('p_management')->where('openid',$inviter)->update($friend);
        return true;
    }

    /**获取自己的世界排名
     * @param $user
     * @return int|mixed|string
     */
    public static function ranking($user){
        $users = Db::name('p_management')->order('total_integral desc')->select();
//        return $users;
        foreach ($users as $key=>$value){
            if($value==$user){
                return $key+1;
            }
        }
    }
}